package com.example.myapplication.nettyheart;


import android.util.Log;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

public class NettyClientHandler extends SimpleChannelInboundHandler<String> {

    public static ChannelHandlerContext context = null;

    //利用写空闲发送心跳检测消息
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        Log.i("dove","发送心跳测试消息");
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case WRITER_IDLE:
//                    Message pingMsg=new Message(MsgType.PING);
//                    ctx.writeAndFlush(JSON.toJSON(pingMsg));
                    String msg = "hello world";
                    byte[] req = msg.getBytes();
                    ByteBuf firstMessage = Unpooled.buffer(req.length);
                    firstMessage.writeBytes(req);
                    ctx.writeAndFlush(firstMessage);
                    System.out.println("send ping to server----------");
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        Log.i("dove","接收心跳测试消息");
    }
}
